package com.zfl.thread.day05;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicIntegerFieldUpdateDemo01 {


    @Data
    @NoArgsConstructor
    private static class BankAccount {

        private volatile int balance;

        private static final AtomicIntegerFieldUpdater<BankAccount> atomicIntegerFieldUpdater =
                AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "balance");

        public void add() {
            atomicIntegerFieldUpdater.getAndIncrement(this);
        }
    }


    public static void main(String[] args) {
        BankAccount bankCount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(50);
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    bankCount.add();
                }
                countDownLatch.countDown();
            }).start();

        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(bankCount.getBalance());

    }
}
